package com.iplus.ydkf.ehome.module.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.avos.avoscloud.SignUpCallback;
import com.iplus.ydkf.ehome.R;
import com.iplus.ydkf.ehome.common.utils.RegexValidateUtil;
import com.iplus.ydkf.ehome.module.MainActivity;
import com.iplus.ydkf.ehome.module.base.BaseActivity;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by liuhaitian on 16/4/19.
 */
public class RegisterActivity extends BaseActivity {
    @Bind(R.id.btn_register_phoneVerify)
    Button mPhoneVerButton;
    @Bind(R.id.et_register_smscode)
    EditText et_register_smscode;
    @Bind(R.id.et_register_username)
    EditText et_register_username;
    @Bind(R.id.et_register_password)
    EditText et_register_password;
    @Bind(R.id.et_register_phone)
    EditText et_register_phone;
    private SmsReciver smsReciver = new SmsReciver();
    String ACTION_SMS_RECIVER = "android.provider.Telephony.SMS_RECEIVED";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mPhoneVerButton.setText(msg.what + "秒后重新发送");
        }
    };

    @OnClick(R.id.btn_register_phoneVerify)
    public void verifyPhoneNumber() {
        if (isEmptyInput())
            return;
        AVQuery<AVUser> query = AVUser.getQuery();
        query.whereEqualTo("mobilePhoneNumber", et_register_phone.getText().toString());
        query.findInBackground(new FindCallback<AVUser>() {
            @Override
            public void done(List<AVUser> list, AVException e) {
                if (isNoException(e)) {
                    if (list.size() == 0) {//如果没有账户,注册账户
                        signUpUser();
                    } else if (!list.get(0).getBoolean("mobilePhoneVerified")) {//如果没有验证,验证号码
                        AVUser.requestMobilePhoneVerifyInBackground(et_register_phone.getText().toString(), new RequestMobileCodeCallback() {
                            @Override
                            public void done(AVException e) {
                                isNoException(e);
                            }
                        });
                    } else {
                        toast("该手机号已注册,请直接登录!");
                    }
                }
            }
        });
        mPhoneVerButton.setEnabled(false);
        new Thread() {
            @Override
            public void run() {
                super.run();
                int time = 60;
                while (time > 0 && time <= 60) {
                    mHandler.sendEmptyMessage(time);
                    time = time - 1;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPhoneVerButton.setText("发送验证码");
                        mPhoneVerButton.setEnabled(true);
                    }
                });
            }
        }.start();
    }

    public void signUpUser() {
        if (isEmptyInput())
            return;
        AVUser user = new AVUser();
        user.setUsername(et_register_phone.getText().toString());
        user.setPassword(et_register_password.getText().toString());
        String phone = et_register_phone.getText().toString();
        user.setMobilePhoneNumber(phone);
        user.put("user_name", et_register_username.getText().toString());
        user.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(AVException e) {
                isNoException(e);
            }
        });
    }

    private boolean isEmptyInput() {
        if (TextUtils.isEmpty(et_register_username.getText().toString())) {
            snackbar("用户名不能为空");
            return true;
        }
        if (TextUtils.isEmpty(et_register_password.getText().toString())) {
            snackbar("密码不能为空");
            return true;
        }
        if (et_register_password.getText().toString().length() < 6 || et_register_password.getText().toString().length() > 12) {
            snackbar("请输入6-12位长度的密码");
            return true;
        }
        if (TextUtils.isEmpty(et_register_phone.getText().toString())) {
            snackbar("手机号不能为空");
            return true;
        }
        if (!RegexValidateUtil.checkCellphone(et_register_phone.getText().toString())) {
            snackbar("请输入正确的手机号");
            return true;
        }
        return false;
    }

    @OnClick(R.id.btn_register)
    public void register() {
        if (isEmptyInput()) {
            return;
        }
        if (TextUtils.isEmpty(et_register_smscode.getText().toString())) {
            snackbar("请输入短信验证码");
        }
        AVUser.verifyMobilePhoneInBackground(et_register_smscode.getText().toString(), new AVMobilePhoneVerifyCallback() {

            @Override
            public void done(AVException e) {
                if (isNoException(e))
                    snackbar("注册成功");
                else {
                    return;
                }
                AVUser.loginByMobilePhoneNumberInBackground(et_register_phone.getText().toString(), et_register_password.getText().toString(), new LogInCallback<AVUser>() {
                    @Override
                    public void done(AVUser avUser, AVException e) {
                        isNoException(e);
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    }
                });
            }
        });
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initView(View view) {
        registSmsReciver();
    }

    @Override
    public void initData(View view) {

    }

    @Override
    public String getFragmentName() {
        return null;
    }


    private void registSmsReciver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SMS_RECIVER);
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        registerReceiver(smsReciver, filter);
    }

    /**
     * 短信广播接受者 用户监听短信，自动填写验证码
     */
    private class SmsReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objs = (Object[]) intent.getExtras().get("pdus");
            for (Object obj : objs) {
                byte[] pdu = (byte[]) obj;
                SmsMessage sms = SmsMessage.createFromPdu(pdu);
                // 短信的内容
                String message = sms.getMessageBody();
                Log.d("log", "message     " + message);
                // 短息的手机号，这里可以进行一个号码的校验
                String from = sms.getOriginatingAddress();
                if (from.contains("1069073"))
                    analysisVerify(message);
                Log.d("log", "from     " + from);
            }
        }

    }

    /**
     * 解析短信并且回写
     *
     * @param message
     */
    private void analysisVerify(String message) {
        try {
            int index = message.indexOf("安全码是");
            String s = (String) message.subSequence(index + 5, index + 5 + 6);
            et_register_smscode.setText(s);
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消短信广播注册
        if (smsReciver != null) {
            unregisterReceiver(smsReciver);
            smsReciver = null;
        }
    }

    public static void goActivity(Context context) {
        context.startActivity(new Intent(context, RegisterActivity.class));
    }
}
